package com.wuyb.serializer;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Redis序列化工具
 *
 * @Author: wyb
 * @Date: 2024/01/03/15:17
 * @Description:
 */
public class RedisKeySerializer implements RedisSerializer<String> {

    /**
     * 编码格式
     */
    private final Charset charset;

    /**
     * Key前缀
     */
    private final String PREFIX_KEY = "meeting_system:";

    public RedisKeySerializer() {
        this(StandardCharsets.UTF_8);
    }

    public RedisKeySerializer(Charset charset) {
        this.charset = charset;
    }

    /**
     * 序列化
     *
     * @param value object to serialize. Can be {@literal null}.
     * @return
     * @throws SerializationException
     */
    @Override
    public byte[] serialize(String value) throws SerializationException {
        String key = PREFIX_KEY + value;
        return key.getBytes(charset);
    }

    /**
     * 反序列化
     *
     * @param bytes object binary representation. Can be {@literal null}.
     * @return
     * @throws SerializationException
     */
    @Override
    public String deserialize(byte[] bytes) throws SerializationException {
        String cacheKey = new String(bytes, charset);
        int indexOf = cacheKey.indexOf(PREFIX_KEY);
        if (indexOf == -1) {
            cacheKey = PREFIX_KEY + cacheKey;
        }
        return (cacheKey.getBytes() == null ? null : cacheKey);
    }
}
